package logic

import (
	"context"
	"encoding/json"
	"time"
	"yk/models/cache"
	"yk/models/mysql"

	"yk/ykrpc/internal/svc"
	"yk/ykrpc/ykrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type YkListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewYkListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *YkListLogic {
	return &YkListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *YkListLogic) YkList(in *ykrpc.YkListRequest) (*ykrpc.YkListResponse, error) {
	// todo: add your logic here and delete this line
	var yk []mysql.Phone
	result, _ := cache.Rdb.Get(cache.Ctx, "yk_list").Result()
	if result != "" {
		json.Unmarshal([]byte(result), &yk)
	} else {
		mysql.DB.Find(&yk)
		mashel, _ := json.Marshal(&yk)
		cache.Rdb.Set(cache.Ctx, "yk_list", mashel, time.Hour*2)
	}

	var yklist []*ykrpc.YkList
	for _, yks := range yk {
		list := ykrpc.YkList{
			Name:    yks.Name,
			Num:     int64(yks.Num),
			Address: yks.Address,
			Id:      int64(yks.ID),
		}
		yklist = append(yklist, &list)
	}

	return &ykrpc.YkListResponse{
		List: yklist,
	}, nil
}
